import { createEntityAdapter, createSlice, Draft, EntityState, nanoid, PayloadAction } from "@reduxjs/toolkit";
import { AppState } from "@store/index";
import { persistReducer } from "redux-persist";
import storage from "redux-persist/lib/storage";

// 搜索历史关键词对象类型
export interface SearchKey {
    id: string;
    name: string;
}

// 搜索历史关键词实体适配器
const searchKeyEntityAdaptor = createEntityAdapter<SearchKey>();

// 搜索历史关键词状态切片
const { reducer: searchKeyReducer, actions } = createSlice<
    EntityState<SearchKey, string>,
    {
        // 添加搜索历史关键词
        addKey(
            state: Draft<EntityState<SearchKey, string>>,
            action: PayloadAction<{ name: string }>
        ): void;
        // 删除搜索历史关键词
        removeKey(
            state: Draft<EntityState<SearchKey, string>>,
            action: PayloadAction<{ id: string }>
        ): void;
        // 清空搜索历史关键词
        clearKey(state: Draft<EntityState<SearchKey, string>>): void;
    },
    "searchKey",
    never
>({
    name: "searchKey",
    initialState: searchKeyEntityAdaptor.getInitialState(),
    reducers: {
        // 添加搜索历史关键词
        addKey(state, action) {
            searchKeyEntityAdaptor.addOne(state, {
                name: action.payload.name,
                id: nanoid(),
            });
        },
        // 删除搜索历史关键词
        removeKey(state, action) {
            searchKeyEntityAdaptor.removeOne(state, action.payload.id);
        },
        // 清空搜索历史关键词
        clearKey(state) {
            searchKeyEntityAdaptor.removeAll(state);
        },
    },
});

// 导出搜索历史关键字状态选择器
export const searchKeySelectors = searchKeyEntityAdaptor.getSelectors<AppState>(
    (state:any) => state.searchKeyReducer
);

// 持久化
const persistSearchKeyReducer = persistReducer(
    { key: "searchKeyReducer", storage },
    searchKeyReducer
);

export default persistSearchKeyReducer;
export const { addKey, removeKey, clearKey } = actions;